import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Descriptions, 
  Tag, 
  Button, 
  Space, 
  Comment, 
  Form, 
  Input, 
  message,
  Spin,
  Avatar,
  List,
  Modal
} from 'antd';
import { 
  EditOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined,
  UserOutlined,
  LinkOutlined,
  FilePdfOutlined,
  EyeOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { useHistory, useParams } from 'react-router-dom';
// 移除有问题的markdown导入
// PDF导出功能暂时移除，等待兼容性问题解决
import api from '../services/api';
import { useUser } from '../contexts/UserContext';

const { TextArea } = Input;

const CaseDetailPage = () => {
  const [caseData, setCaseData] = useState(null);
  const [comments, setComments] = useState([]);
  const [relatedResources, setRelatedResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const history = useHistory();
  const { id } = useParams();
  const { user } = useUser();

  // 获取案例详情
  const fetchCaseDetail = async () => {
    setLoading(true);
    try {
      const response = await api.get(`/cases/${id}`);
      setCaseData(response.data);
      
      // 获取关联资源
      await fetchRelatedResources();
    } catch (error) {
      console.error('获取案例详情失败:', error);
      message.error('获取案例详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取关联资源
  const fetchRelatedResources = async () => {
    try {
      const response = await api.get('/resources');
      const resources = response.data || [];
      const related = resources.filter(r => r.related_case_id === parseInt(id));
      setRelatedResources(related);
    } catch (error) {
      console.error('获取关联资源失败:', error);
    }
  };

  // 导出PDF
  const handleExportPDF = async () => {
    try {
      setLoading(true);
      message.loading('正在生成PDF...', 0);
      
      // 创建一个临时的div用于渲染PDF内容
      const tempDiv = document.createElement('div');
      tempDiv.style.width = '210mm';
      tempDiv.style.padding = '20px';
      tempDiv.style.backgroundColor = 'white';
      tempDiv.style.fontFamily = 'Arial, sans-serif';
      tempDiv.style.fontSize = '14px';
      tempDiv.style.lineHeight = '1.6';
      tempDiv.style.position = 'absolute';
      tempDiv.style.left = '-9999px';
      tempDiv.style.top = '-9999px';
      
      // 构建PDF内容
      tempDiv.innerHTML = `
        <div style="margin-bottom: 30px; border-bottom: 2px solid #1890ff; padding-bottom: 20px;">
          <h1 style="color: #1890ff; margin: 0; font-size: 24px;">${caseData.title}</h1>
          <div style="margin-top: 10px; color: #666;">
            <span>案例ID: ${caseData.id}</span> | 
            <span>分类: ${caseData.category}</span> | 
            <span>状态: ${caseData.approved ? '已审核' : '待审核'}</span>
          </div>
          <div style="margin-top: 5px; color: #666;">
            <span>创建时间: ${new Date(caseData.created_at).toLocaleString()}</span>
          </div>
          ${caseData.keywords ? `<div style="margin-top: 10px;"><strong>关键词:</strong> ${caseData.keywords}</div>` : ''}
        </div>
        
        <div style="margin-bottom: 30px;">
          <h2 style="color: #1890ff; font-size: 18px; margin-bottom: 10px;">问题描述</h2>
          <div style="background: #f5f5f5; padding: 15px; border-radius: 4px; white-space: pre-wrap;">${caseData.description}</div>
        </div>
        
        <div style="margin-bottom: 30px;">
          <h2 style="color: #1890ff; font-size: 18px; margin-bottom: 10px;">解决方案</h2>
          <div style="background: #f9f9f9; padding: 15px; border-radius: 4px;">
            ${caseData.solution ? caseData.solution.replace(/\n/g, '<br>').replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>') : '暂无解决方案'}
          </div>
        </div>
        
        ${relatedResources.length > 0 ? `
        <div style="margin-bottom: 30px;">
          <h2 style="color: #1890ff; font-size: 18px; margin-bottom: 10px;">相关资源</h2>
          <div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">
            ${relatedResources.map(resource => `
              <div style="margin-bottom: 10px; padding: 10px; background: white; border-radius: 4px;">
                <strong>${resource.name}</strong> (${resource.type})
                ${resource.description ? `<br><span style="color: #666;">${resource.description}</span>` : ''}
                ${resource.version ? `<br><span style="color: #999;">版本: ${resource.version}</span>` : ''}
              </div>
            `).join('')}
          </div>
        </div>` : ''}
        
        <div style="margin-top: 40px; text-align: center; color: #999; font-size: 12px; border-top: 1px solid #ddd; padding-top: 20px;">
          <div>导出时间: ${new Date().toLocaleString()}</div>
          <div>Integrated Trouble Tracking System</div>
        </div>
      `;
      
      document.body.appendChild(tempDiv);
      
      // 使用html2canvas转换为图片
      const canvas = await html2canvas(tempDiv, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff'
      });
      
      // 移除临时div
      document.body.removeChild(tempDiv);
      
      // 创建PDF
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 170; // A4宽度减去边距
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      
      pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 20, 20, imgWidth, imgHeight);
      
      // 下载PDF
      pdf.save(`案例-${caseData.title}-${new Date().toISOString().split('T')[0]}.pdf`);
      
      message.destroy();
      message.success('PDF导出成功');
    } catch (error) {
      console.error('导出PDF失败:', error);
      message.destroy();
      message.error('导出PDF失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCaseDetail();
  }, [id]);

  const handleAddComment = async (values) => {
    try {
      // 这里应该调用API添加评论
      // 暂时使用模拟数据
      const newComment = {
        author: user?.username || '当前用户',
        avatar: <Avatar icon={<UserOutlined />} />,
        content: values.content,
        datetime: new Date().toLocaleString()
      };
      setComments([...comments, newComment]);
      form.resetFields();
      message.success('评论添加成功');
    } catch (error) {
      console.error('添加评论失败:', error);
      message.error('添加评论失败');
    }
  };

  if (loading) {
    return <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />;
  }

  if (!caseData) {
    return <div>案例不存在</div>;
  }

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<EditOutlined />} onClick={() => history.push(`/cases/${id}/edit`)}>
          编辑
        </Button>
        <Button 
          icon={<FilePdfOutlined />} 
          onClick={() => message.info('PDF导出功能暂时不可用，请稍后再试')}
          disabled
        >
          导出PDF
        </Button>
      </Space>

      <Card title={caseData.title} style={{ marginBottom: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="案例ID">{caseData.id}</Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={caseData.approved ? 'green' : 'orange'}>
              {caseData.approved ? '已审核' : '待审核'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="分类">{caseData.category}</Descriptions.Item>
          <Descriptions.Item label="创建者">{caseData.created_by}</Descriptions.Item>
          <Descriptions.Item label="关键词">{caseData.keywords || '无'}</Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {new Date(caseData.created_at).toLocaleString()}
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            {new Date(caseData.updated_at).toLocaleString()}
          </Descriptions.Item>
        </Descriptions>

        <div style={{ marginTop: 24 }}>
          <h3>问题描述</h3>
          <p>{caseData.description}</p>
        </div>

        <div style={{ marginTop: 24 }}>
          <h3>解决方案</h3>
          <div style={{
            border: '1px solid #d9d9d9',
            borderRadius: '6px',
            padding: '16px',
            backgroundColor: '#fafafa'
          }}>
            {caseData.solution ? (
              <div 
                style={{ 
                  backgroundColor: 'transparent',
                  lineHeight: '1.6',
                  whiteSpace: 'pre-wrap'
                }}
                dangerouslySetInnerHTML={{
                  __html: caseData.solution
                    .replace(/\n/g, '<br>')
                    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
                    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
                    .replace(/^# (.+)$/gm, '<h1 style="color: #1890ff; margin: 16px 0 8px 0;">$1</h1>')
                    .replace(/^## (.+)$/gm, '<h2 style="color: #1890ff; margin: 14px 0 6px 0;">$1</h2>')
                    .replace(/^- (.+)$/gm, '• $1')
                    .replace(/```([^`]+)```/g, '<pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>$1</code></pre>')
                }}
              />
            ) : (
              <span style={{ color: '#999' }}>暂无解决方案</span>
            )}
          </div>
        </div>
      </Card>

      <Card title="相关资源" style={{ marginBottom: 16 }}>
        {relatedResources.length > 0 ? (
          <List
            dataSource={relatedResources}
            renderItem={(resource) => (
              <List.Item
                actions={[
                  <Button 
                    type="link" 
                    size="small"
                    onClick={() => window.open(resource.path, '_blank')}
                  >
                    下载
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={resource.name}
                  description={
                    <div>
                      <Tag color="blue">{resource.type}</Tag>
                      {resource.version && <Tag color="green">{resource.version}</Tag>}
                      {resource.description && (
                        <div style={{ marginTop: 4, color: '#666' }}>
                          {resource.description}
                        </div>
                      )}
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        ) : (
          <p style={{ textAlign: 'center', color: '#999', margin: '40px 0' }}>
            暂无关联资源
          </p>
        )}
      </Card>

      <Card title="评论">
        {comments.map((comment, index) => (
          <Comment
            key={index}
            author={comment.author}
            avatar={comment.avatar}
            content={comment.content}
            datetime={comment.datetime}
          />
        ))}

        <Comment
          avatar={<Avatar icon={<UserOutlined />} />}
          content={
            <Form form={form} onFinish={handleAddComment}>
              <Form.Item name="content" rules={[{ required: true, message: '请输入评论内容' }]}>
                <TextArea rows={4} placeholder={user ? `以 ${user.username} 身份发表评论...` : '请输入评论内容...'} />
              </Form.Item>
              <Form.Item>
                <Button htmlType="submit" type="primary">
                  添加评论
                </Button>
              </Form.Item>
            </Form>
          }
        />
      </Card>
    </div>
  );
};

export default CaseDetailPage;